package com.newtest.demos.Service.impl;

import com.newtest.demos.mapper.LoginMapper;
import com.newtest.demos.Service.LoginService;
import com.newtest.demos.pojo.LoginUser;
import com.newtest.demos.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Optional;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private LoginMapper loginMapper;

    @Override
    public LoginUser login(LoginUser loginUser) {
        return loginMapper.getByUsernameAndPassword(loginUser);
    }

    @Override
    public void registerUser(LoginUser loginUser) {
        //直接储存信息

        loginMapper.insertUser(loginUser);

    }

    @Override
    public int updateUser(LoginUser loginUser) {
        return loginMapper.updateUser(loginUser);
    }

    @Override
    public int deleteUser(LoginUser loginUser) {
        return loginMapper.deleteUser(loginUser);
    }

    @Override
        public String username(HttpServletRequest request){

            //        获取请求对象和响应对象
            HttpServletRequest req = (HttpServletRequest) request;
            HttpServletRequest resp = (HttpServletRequest) request;
//        获取请求头令牌
            String jwt = req.getHeader("token");
            //解析令牌
            Claims claims = JwtUtils.parseJWT(jwt);
            // 使用get方法提取username属性，这里我们假设username属性是String类型
            String username = claims.get("username", String.class);
            return username;

    }

    @Override
    public boolean isUsernameExists(String username) {
        return loginMapper.isUsernameExists(username) > 0;
    }

    @Override
    public boolean isEmailExists(String email) {
        return loginMapper.isEmailExists(email) > 0;
    }

    public List<LoginUser> findAllUser(String username) {
//        LoginUser user = loginMapper.findAllUser(username);
        return loginMapper.findAllUser(username);
    }

//    @Override
//    public boolean isUsernameAvailable(String username) {
//        return loginMapper.findUserByUsername(username);
//    }


}
